package com.googleplay.billing;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;

import com.googleplay.billing.BillingService.RequestPurchase;
import com.googleplay.billing.Consts.PurchaseState;
import com.googleplay.billing.Consts.ResponseCode;
import com.imoblife.brainwavestus.obpurchaseSystem.OBpurchaseSystem;
import com.imoblife.brainwavestus.users.UsersUtil;

public class RestoreTransactions {

	private BillingService mBillingService;

	private Handler mHandler;

	private PurchaseObserver mPurchaseObserver;

	private Activity mActivity;

	public RestoreTransactions(Activity activity) {
		mActivity = activity;
		mHandler = new Handler();
		initPurchaseObserver();
		mBillingService = new com.googleplay.billing.BillingService();
		mBillingService.setContext(mActivity);
		ResponseHandler.register(mPurchaseObserver);
	}

	public void restoreTransactions() {
		mBillingService.checkBillingSupported(Consts.ITEM_TYPE_SUBSCRIPTION);
	}

	private void initPurchaseObserver() {

		mPurchaseObserver = new PurchaseObserver(mActivity, mHandler) {

			public void onRequestPurchaseResponse(RequestPurchase request,
					ResponseCode responseCode) {

			}

			public void onPurchaseStateChange(PurchaseState purchaseState,
					String itemId, int quantity, long purchaseTime,
					String developerPayload) {
				
				Log.d("googlePlay", purchaseState+" "+itemId);
				

			}

			public void onBillingSupported(boolean supported, String type) {
				Log.d("googlePlay", type+" "+supported);
				if (Consts.ITEM_TYPE_SUBSCRIPTION.equals(type)) {

					if (supported) {
						mBillingService.restoreTransactions();
					} else {
						mBillingService
								.checkBillingSupported(Consts.ITEM_TYPE_INAPP);
					}

				} else if (Consts.ITEM_TYPE_INAPP.equals(type)) {

					if (supported) {
						mBillingService.restoreTransactions();
					}
				}

				if (!supported) {
					restoreTapjoyProductIds();
				}

			}

			public void onRestoreTransactionsResponse(
					com.googleplay.billing.BillingService.RestoreTransactions request,
					ResponseCode responseCode) {
				Log.d("googlePlay", request+" "+responseCode);
				restoreTapjoyProductIds();
			}
		};

	}

	private void restoreTapjoyProductIds() {

		new Thread() {

			public void run() {

				OBpurchaseSystem.getOBpurchaseSystem(mActivity)
						.restoreTransactions(mActivity);
				mActivity.sendBroadcast(new Intent(
						UsersUtil.UPDATE_LIBRERY_CATEGOTY));

			};
		}.start();

	}

	public void release() {
		ResponseHandler.unregister(mPurchaseObserver);
		mBillingService.unbind();
	}

}
